<?php

// +----------------------------------------------------------
// | Name： 星空后台 上传服务管理
// +----------------------------------------------------------
// | Version: V5.0
// +----------------------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +----------------------------------------------------------
// | Time: 2021-04-15 10:08
// +----------------------------------------------------------
declare(strict_types=1);

namespace app\common\services;

use app\common\services\OSS;

/**
 * @xk 上传服务
 */
class UploadServices
{
    /**
     * @xk 执行图片上传
     *
     * @method doUpload
     *
     * @param [type] $act     [description]
     * @param [type] $path    [description]
     * @param [type] $picname [description]
     * @param [type] $pictemp [description]
     * @param [type] $title   [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-15T10:27:02+080
     */
    public static function doUpload($act, $picname, $pictemp, $pictype, $picsize, $title)
    {
        // 获取上传配置
        $upload_config = config('upload');
        $maxsize = $upload_config['upload_'.$act.'_size'];
        $allowtype = $upload_config['upload_'.$act.'_type'];
        $result = [];
        $result['result_code'] = 200;
        $result['result_msg'] = '上传成功';
        $result['resultData'] = [];
        // 判断上传类型是否允许
        if (!in_array($pictype, $allowtype)) {
            $result['result_code'] = 404;
            $result['result_msg'] = '类型不正确';
            $result['resultData'] = [];

            return $result;
        }
        if ($picsize > $maxsize) {
            $result['result_code'] = 404;
            $result['result_msg'] = '大小不符合，系统最大允许上传'.bytesChanage($maxsize).'的文件';
            $result['resultData'] = [];

            return $result;
        }
        $path = 'upload/'.$act.'/'.date('Ymd');
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        $upload_type = config('system_config.upload_type');
        if($act == 'file'){
          $upload_type = 0;
        }
        switch ($upload_type) {
          case '0':
            // 本地上传
            $res = self::ownerUpload($path, $picname, $pictemp);
            break;
          case '1':
            // 阿里云 OSS
            $res = self::alOss($path, $picname, $pictemp);
            break;
          case '2':
            // 七牛云 OSS
            $res = self::qnOss($path, $picname, $pictemp);
            break;
          case '3':
            // 腾讯云 OSS
            $res = txOss($paht, $picname, $pictemp);
            break;
        }
        $result['result_code'] = $res['result_code'];
        $result['result_msg'] = $res['result_msg'];
        $result['resultData']['title'] = $title;
        $result['resultData']['upload_url'] = $res['upload_url'];
        $result['resultData']['show_url'] = getShowUrl($res['upload_url']);
        return $result;
    }
    /**
     * @xk base64图片格式上传
     *
     * @method doBase64Upload
     * @param  string         $act                       [description]
     * @param  string         $imgBase64                 [description]
     * @return [type]         [description]
     * @Time   2021-08-24
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public static function doBase64Upload($act='image', $imgBase64='')
    {
        $result = [];
        $result['result_code'] = 200;
        $result['result_msg'] = '上传成功';
        $result['resultDtat'] = [];
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgBase64, $res)) {
            //获取图片类型
            $type = $res[2];
            $path = 'upload/'.$act.'/'.date('Ymd');
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            // 开始判断上传方式
            $upload_type = config('system_config.upload_type');
            switch ($upload_type) {
            case '0':
              if (in_array($type, ['pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'])) {
                  $new_file = $path.'/'.md5(time().rand(11111, 99999)).'.'.$type;
                  if (file_put_contents($new_file, base64_decode(str_replace($res[1], '', $imgBase64)))) {
                    $res['result_code'] = 200;
                    $res['result_msg'] = '上传成功';
                    $res['upload_url'] = '/'.$new_file;
                  } else {
                    $result['result_code'] = 404;
                    $result['result_msg'] = '上传出错，请重试';
                    return $result;
                  }
              } else {
                  $result['result_code'] = 404;
                  $result['result_msg'] = '上传出错，请重试';
                  return $result;
              }
              break;
            case '1':
              // 临时文件
              $pictemp = tempnam("/tmp/", "FOO");
              //保存图片
              $handle = fopen($pictemp, "w");
              $picname = date('YmdHis').'.'.$type;
              if (fwrite($handle, base64_decode(str_replace($res[1], '', $imgBase64)))) {
                  $res = self::alOss($path, $picname, $pictemp);
              } else {
                  $result['result_code'] = 404;
                  $result['result_msg'] = '上传出错，请重试';
                  return $result;
              }
              break;
            case '2':
              // 临时文件
              $pictemp = tempnam("/tmp/", "FOO");
              //保存图片
              $handle = fopen($pictemp, "w");
              $picname = date('YmdHis').'.'.$type;
              if (fwrite($handle, base64_decode(str_replace($res[1], '', $imgBase64)))) {
                  $res = self::qnOss($path, $picname, $pictemp);
              } else {
                  $result['result_code'] = 404;
                  $result['result_msg'] = '上传出错，请重试';
                  return $result;
              }
              break;
            case '3':
              // 临时文件
              $pictemp = tempnam("/tmp/", "FOO");
              //保存图片
              $handle = fopen($pictemp, "w");
              $picname = date('YmdHis').'.'.$type;
              if (fwrite($handle, base64_decode(str_replace($res[1], '', $imgBase64)))) {
                  $res = self::txOss($path, $picname, $pictemp);
              } else {
                  $result['result_code'] = 404;
                  $result['result_msg'] = '上传出错，请重试';
                  return $result;
              }
              break;
          }
            $result['result_code'] = $res['result_code'];
            $result['result_msg'] = $res['result_msg'];
            $result['resultData']['picurl'] = $res['upload_url'];
            $result['resultData']['show_picurl'] = getShowUrl($res['upload_url']);
            return $result;
        } else {
            $result['result_code'] = 404;
            $result['result_msg'] = '图片格式错误';
            return $result;
        }
    }

    /**
     * @xk 执行本地上传
     *
     * @method ownerUpload
     *
     * @param [type] $path    [description]
     * @param [type] $picname [description]
     * @param [type] $pictemp  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-15T10:48:14+080
     */
    public static function ownerUpload($path, $picname, $pictemp)
    {
        $typex = strrchr($picname, '.');
        $lastpath = $path.'/'.md5(time().rand(11111, 99999)).$typex;
        try {
            $res = move_uploaded_file($pictemp, $lastpath);
            $result = '/'.$lastpath;

            return ['result_code' => 200, 'result_msg' => '上传成功', 'upload_url' => $result];
        } catch (\Exception $e) {
            return ['result_code' => 404, 'result_msg' => $e->getMessage(), 'upload_url'=>''];
        }
    }
    /**
     * @xk 阿里云OSS上传
     *
     * @method alOss
     * @param  [type]                  $path                     [description]
     * @param  [type]                  $picname                  [description]
     * @param  [type]                  $pictemp                  [description]
     * @return [type]                                            [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-07-14T15:07:07+080
     */
    public static function alOss($path, $picname, $pictemp)
    {
        $oss = new OSS();
        $typex = strrchr($picname, '.');
        $lastpath = $path.'/'.md5(time().rand(11111, 99999)).$typex;
        try {
            $oss->checkBucket();
            $oss->fileUpload($lastpath, $pictemp);
            // move_uploaded_file($pictemp, $lastpath);
            $result = '/'.$lastpath;
            return ['result_code' => 200, 'result_msg' => '上传成功', 'upload_url' => $result];
        } catch (\Exception $e) {
            return ['result_code' => 404, 'result_msg' => $e->getMessage(), 'upload_url'=>''];
        }
    }
    /**
     * @xk 清除文件
     *
     * @method destroyUrl
     * @param  [type]     $path                      [description]
     * @return [type]     [description]
     * @Time   2021-08-17
     * @City   qingdao
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function destroyUrl($path)
    {
        $upload_type = config('system_config.upload_type');
        switch ($upload_type) {
        case '0':
          // 本地上传
          try {
              $res = unlink('.'.$path);
              return ['result_code' => 200, 'result_msg' => '图片清除成功', 'upload_url'=>''];
          } catch (\Exception $e) {
              return ['result_code' => 404, 'result_msg' => $e->getMessage(), 'upload_url'=>''];
          }
          break;
        case '1':
          $oss = new OSS();
          try {
              $oss->checkBucket();
              $oss->destroyUrl($path);
              return ['result_code' => 200, 'result_msg' => '图片清除成功', 'upload_url'=>''];
          } catch (\Exception $e) {
              return ['result_code' => 404, 'result_msg' => $e->getMessage(), 'upload_url'=>''];
          }
          break;
        case '2':
          // 七牛云 OSS
          $res = self::qnOss($path, $picname, $pictemp);
          break;
        case '3':
          // 腾讯云 OSS
          $res = txOss($paht, $picname, $pictemp);
          break;
      }
    }
}
